package com.shengzhe.ostudent.service.sysuser;

import com.shengzhe.ostudent.common.exception.OsException;
import com.shengzhe.ostudent.dao.sysuser.SysUserDao;
import com.shengzhe.ostudent.dao.sysuser.SysUserDaoImpl;
import com.shengzhe.ostudent.entity.SysUser;
import com.shengzhe.ostudent.entity.SysUserCondition;
import com.shengzhe.ostudent.utils.MD5Utils;
import com.shengzhe.ostudent.utils.result.E;
import com.shengzhe.ostudent.utils.security.JwtUtils;

import java.util.List;

public class SysUserServiceImpl implements SysUserService {
    private final SysUserDao sysUserDao = new SysUserDaoImpl();

    @Override
    public boolean register(SysUser sysUser) {
        SysUserCondition sysUserCondition = new SysUserCondition();
        sysUserCondition.setPhone(sysUser.getPhone());
        if (list(sysUserCondition).isEmpty()) {
            return sysUserDao.register(sysUser);
        } else {
            throw new OsException(E.USER_CODE_N42);
        }
    }

    @Override
    public List<SysUser> list(SysUserCondition sysUserCondition) {
        return sysUserDao.list(sysUserCondition);
    }

    @Override
    /**
     * 系统用户的登录方法
     * 根据传递的参数role对象的phone，通过list方法查询其password，如果role的password与其查询出的对象的password相同
     * 则认为登录成功,否则登录失败。
     */
    public String login(SysUser sysUser) {
        //定义SysUser的查询对象
        SysUserCondition sysUserCondition = new SysUserCondition();
        //把查询对象的phone值设置为登录用户sysUser的phone值
        sysUserCondition.setPhone(sysUser.getPhone());
        //在数据库中根据phone值查询相关数据
        List<SysUser> sysUserList = list(sysUserCondition);
        //如果查询结果为空，则抛出异常，异常显示该用户没有注册
        if (sysUserList.isEmpty()) {
            throw new OsException(E.USER_CODE_N50);
        }
        //有查询结果，说明改手机号已经被注册，需要核实密码是否一致，如果一致则登陆成功
        //此时注意，由于数据库中密码已加密，登录密码应该使用MD5算法加密，再与数据库中密码比较。
        SysUser sysUserLogin = sysUserList.get(0);
        if (sysUserLogin.getPassword().equals(MD5Utils.encryptMD5(sysUser.getPassword()))) {
            return JwtUtils.createToken(sysUserLogin.getId());
        } else {
            throw new OsException(E.USER_CODE_N49);
        }
    }
}
